/**
 * EduVerse Credentials - API服务
 * 
 * 处理前端与后端API的数据交互
 */

// API地址前缀
const API_BASE_URL = 'http://localhost:3000';

// 钱包API
const walletApi = {
  // DID相关
  createPolygonId: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/dids/create-polygonid`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API错误 (${response.status}): ${errorText}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error('创建DID失败:', error);
      throw error;
    }
  },
  
  createEthrId: async (network) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/dids/create-ethr`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ network })
      });
      return await response.json();
    } catch (error) {
      console.error('创建Ethr DID失败:', error);
      throw error;
    }
  },
  
  listDids: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/dids`);
      return await response.json();
    } catch (error) {
      console.error('获取DID列表失败:', error);
      throw error;
    }
  },
  
  // 凭证相关
  receiveCredential: async (credential) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/credentials`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ credential })
      });
      return await response.json();
    } catch (error) {
      console.error('接收凭证失败:', error);
      throw error;
    }
  },
  
  listCredentials: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/credentials`);
      return await response.json();
    } catch (error) {
      console.error('获取凭证列表失败:', error);
      throw error;
    }
  },
  
  getCredential: async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/credentials/${id}`);
      return await response.json();
    } catch (error) {
      console.error(`获取凭证${id}失败:`, error);
      throw error;
    }
  },
  
  deleteCredential: async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/credentials/${id}`, {
        method: 'DELETE'
      });
      return await response.json();
    } catch (error) {
      console.error(`删除凭证${id}失败:`, error);
      throw error;
    }
  },
  
  // ZKP相关
  generateProof: async (proofRequest, holderDid, credentialId) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/proofs/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ proofRequest, holderDid, credentialId })
      });
      return await response.json();
    } catch (error) {
      console.error('生成ZKP证明失败:', error);
      throw error;
    }
  },
  
  // VP相关
  createPresentation: async (data) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/presentations/create`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      return await response.json();
    } catch (error) {
      console.error('创建可验证演示失败:', error);
      throw error;
    }
  },
  
  // 导入凭证
  importCredential: async (credential, format = 'w3c') => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/wallet/credentials/import`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ credential, format })
      });
      return await response.json();
    } catch (error) {
      console.error('导入凭证失败:', error);
      throw error;
    }
  }
};

// 发行方API
const issuerApi = {
  // DID相关
  createIssuerIdentity: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/dids/create`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      return await response.json();
    } catch (error) {
      console.error('创建发行方身份失败:', error);
      throw error;
    }
  },
  
  getCurrentIssuerDID: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/dids/current`);
      return await response.json();
    } catch (error) {
      console.error('获取当前发行方DID失败:', error);
      throw error;
    }
  },
  
  publishIssuerState: async (rhsUrl) => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/dids/publish-state`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ rhsUrl })
      });
      return await response.json();
    } catch (error) {
      console.error('发布发行方状态失败:', error);
      throw error;
    }
  },
  
  // Schema相关
  createSchema: async (schema) => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/schemas`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(schema)
      });
      return await response.json();
    } catch (error) {
      console.error('创建Schema失败:', error);
      throw error;
    }
  },
  
  listSchemas: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/schemas`);
      return await response.json();
    } catch (error) {
      console.error('获取Schema列表失败:', error);
      throw error;
    }
  },
  
  getSchema: async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/schemas/${id}`);
      return await response.json();
    } catch (error) {
      console.error(`获取Schema ${id}失败:`, error);
      throw error;
    }
  },
  
  // 凭证发行相关
  issueCredential: async (credentialData) => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/credentials/issue`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentialData)
      });
      return await response.json();
    } catch (error) {
      console.error('发行凭证失败:', error);
      throw error;
    }
  },
  
  listCredentials: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/credentials`);
      return await response.json();
    } catch (error) {
      console.error('获取发行的凭证列表失败:', error);
      throw error;
    }
  },
  
  // 撤销凭证
  revokeCredential: async (id, method = 'w3c-status-list') => {
    try {
      const response = await fetch(`${API_BASE_URL}/issuer/api/issuer/credentials/${id}/revoke`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ method })
      });
      return await response.json();
    } catch (error) {
      console.error(`撤销凭证${id}失败:`, error);
      throw error;
    }
  }
};

// 验证方API
const verifierApi = {
  // 证明请求相关
  createAgeProofRequest: async (data) => {
    try {
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/proof-requests/age`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      return await response.json();
    } catch (error) {
      console.error('创建年龄证明请求失败:', error);
      throw error;
    }
  },
  
  createDegreeProofRequest: async (data) => {
    try {
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/proof-requests/degree`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      return await response.json();
    } catch (error) {
      console.error('创建学位证明请求失败:', error);
      throw error;
    }
  },
  
  createMTPProofRequest: async (data) => {
    try {
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/proof-requests/mtp`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      return await response.json();
    } catch (error) {
      console.error('创建MTP证明请求失败:', error);
      throw error;
    }
  },
  
  getProofRequest: async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/proof-requests/${id}`);
      return await response.json();
    } catch (error) {
      console.error(`获取证明请求${id}失败:`, error);
      throw error;
    }
  },
  
  // VP验证相关
  verifyPresentation: async (presentation, requestId) => {
    try {
      console.log("发送验证请求到后端API，数据:", { presentation, requestId });
      const requestData = { presentation };
      if (requestId) {
        requestData.requestId = requestId;
      }
      
      console.log("完整请求数据:", JSON.stringify(requestData));
      
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/verify`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });
      
      console.log("API响应状态:", response.status, response.statusText);
      
      if (!response.ok) {
        const errorText = await response.text();
        console.error(`验证请求失败，状态码: ${response.status}，错误:`, errorText);
        throw new Error(`服务器响应错误: ${response.status} ${response.statusText} - ${errorText}`);
      }
      
      const data = await response.json();
      console.log("验证API响应数据:", data);
      return data;
    } catch (error) {
      console.error('验证可验证演示失败:', error);
      throw error;
    }
  },
  
  // 批量验证多个VP
  verifyBatchPresentations: async (presentations) => {
    try {
      console.log("发送批量验证请求到后端API，数据:", { presentations });
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/verify-batch`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ presentations })
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        console.error(`批量验证请求失败，状态码: ${response.status}，错误:`, errorText);
        throw new Error(`服务器响应错误: ${response.status} ${response.statusText}`);
      }
      
      const data = await response.json();
      console.log("批量验证API响应数据:", data);
      return data;
    } catch (error) {
      console.error('批量验证可验证演示失败:', error);
      throw error;
    }
  },
  
  // 验证单个VC
  verifyCredential: async (credential) => {
    try {
      console.log("发送凭证验证请求到后端API，数据:", { credential });
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/verify-credential`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ credential })
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        console.error(`凭证验证请求失败，状态码: ${response.status}，错误:`, errorText);
        throw new Error(`服务器响应错误: ${response.status} ${response.statusText}`);
      }
      
      const data = await response.json();
      console.log("凭证验证API响应数据:", data);
      return data;
    } catch (error) {
      console.error('验证可验证凭证失败:', error);
      throw error;
    }
  },
  
  getVerificationResult: async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/verifier/api/verifier/verification-results/${id}`);
      return await response.json();
    } catch (error) {
      console.error(`获取验证结果${id}失败:`, error);
      throw error;
    }
  }
};

export { walletApi, issuerApi, verifierApi }; 